import requests
from functools import wraps
from django.conf import settings
from .migrations import (
    CATEGORY_AUTH, CATEGORY_TERMINAL, CATEGORY_MAIL,
    CATEGORY_SHARE, CATEGORY_DOWNLOAD, CATEGORY_RESOURCE
)


def apply_strategy(view_func):
    @wraps(view_func)
    def wrapper(*args, **kwargs):
        response = view_func(*args, **kwargs)
        if 200 <= response.status_code < 300:
            data = response.data
            uid = data['uid']
            url = None
            # 身份认证策略、终端安全策略以及资源访问策略下发到CAS
            if (
                uid.startswith(CATEGORY_AUTH[1])
                or uid.startswith(CATEGORY_TERMINAL[1])
                or uid.startswith(CATEGORY_RESOURCE[1])
            ):
                url = settings.CAS['SERVER'] + settings.CAS['ENABLE_STRATEGY']
            if url:
                res = requests.post(url, json={'uid': data['uid'], 'enabled': data['enabled']})
                if res.status_code >= 400:
                    response.status_code = 502
        return response
    return wrapper


def _perform_reload():
    # 先用同步的方式实现，之后看并发情况再决定要不要上Celery
    try:
        reload_url = settings.CAS['SERVER'] + settings.CAS['RELOAD']
        requests.get(reload_url, timeout=2, verify=not settings.DEBUG)
    except Exception as e:
        # TODO take a log
        print('reload CAS resource state failed, %s' % e)


def reload_cas(view_func=None):
    """可以通过函数的形式调用，也可以装饰器方式调用"""
    if view_func is None:  # 函数形式
        _perform_reload()
    else:  # 装饰器形式
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            response = view_func(request, *args, **kwargs)
            if 200 <= response.status_code < 300:
                _perform_reload()
            return response
        return wrapper
